package gray.android.field;

import gray.Field;
import gray.android.FactoryAndroid;
import regex.Regex;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import snippet.Snipet;

public class TelephoneField extends LinearLayout implements Field<String,View>, TextWatcher{
	private final EditText _field;
	private final Boolean _required;
  private final Snipet _lang;
	
	private TelephoneField(Context context,final Snipet lang, String name, Character key, Boolean required) {
		super(context);
		TextView txt = new TextView(context);
		txt.setText(name);
    txt.setTextColor(0xFF000000);
		_field = new EditText(context);
		_field.addTextChangedListener(this);
		_field.setLines(1);
		//requestFocus();
    _field.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
                                            LayoutParams.WRAP_CONTENT));
		
		addView(txt);
		addView(_field);
		_required = required;
    _lang=lang;
	}

	public static Field<String, View> factory(Context context, final Snipet lang, String name, Character key){
		return new TelephoneField(context,lang, name, key, false);
	}

	public static Field<String, View> factoryRequired(Context context, final Snipet lang, String name, Character key){
		return new TelephoneField(context,lang, name, key, true);
	}
	
	@Override
	public View container() {
		// TODO Auto-generated method stub
		return this;
	}

	@Override
	public Boolean ready() {
		if (_field.getText().toString().length()==0)
			return !_required;
		return Regex.validateTelephone(_field.getText().toString());
	}

	@Override
    public String input() {
      return _field.getText().toString();
    }
	
	@Override
	public void afterTextChanged(Editable arg0) {
		if (!Regex.validateTelephone(_field.getText().toString())){
			FactoryAndroid.message(this.getContext(), _lang.notTelephone());
			_field.setTextColor(0xFFFF0000);
		}else{
			_field.setTextColor(0xFF000000);
		}
	}

	@Override
	public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
			int arg3) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// TODO Auto-generated method stub
		
	}
}
